from skimage import io
from matplotlib import pyplot as plt
import numpy as np 

# 指定图像路径
image_path = r'C:\Users\26356\Desktop\python\lena.jpg'

# 读取图像
image = io.imread(image_path)

# 初始化灰度图像
max_gray = np.zeros(image.shape[0:2],dtype='uint8')
ave_gray = np.zeros(image.shape[0:2],dtype='uint8')
weight_gray = np.zeros(image.shape[0:2],dtype='uint8')
max_weight_gray = np.zeros(image.shape[0:2],dtype='uint8')
min_weight_gray = np.zeros(image.shape[0:2],dtype='uint8')
for ii in range(image.shape[0]):
    for jj in range(image.shape[1]):
        r, g, b = image[ii, jj, :]
        #最大值法
        max_gray[ii, jj] = max(r, g, b) 
        #平均值法
        ave_gray[ii, jj] = (r + g + b)/3
        #加权平均法
        weight_gray[ii, jj] = 0.30 * r + 0.59 * g + 0.11 * b
        #最大值加权法
        max_weight_gray[ii, jj] = 0.5 * max(r, g, b) + 0.5 * (r + g + b)/3
        #最小值加权法
        min_weight_gray[ii, jj] = 0.5 * min(r, g, b) + 0.5 * (r + g + b)/3

plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False
plt.subplot(3,3,1)
plt.axis('off') 
plt.imshow(image)
plt.title('彩色图像')
plt.subplot(3,3,2)
plt.axis('off') 
plt.imshow(max_gray, cmap='gray')
plt.title('最大值法')
plt.subplot(3,3,3)
plt.axis('off')
plt.imshow(ave_gray, cmap='gray')
plt.title('平均值法')
plt.subplot(3,3,4)
plt.axis('off') 
plt.imshow(weight_gray, cmap='gray')
plt.title('加权平均法')
plt.subplot(3,3,5)
plt.axis('off') 
plt.imshow(max_weight_gray, cmap='gray')
plt.title('最大值加权法')
plt.subplot(3,3,6)
plt.axis('off') 
plt.imshow(min_weight_gray, cmap='gray')
plt.title('最小值加权法')
plt.savefig('lena灰度化.tif')
plt.show()
